<template>
  <div class="home-page" ref="homePage">
    <el-container>
      <!-- 顶栏 -->
      
      <el-header height="60px">
        <div class="headerDiv">
          <!-- <span>菜单</span> -->
          <h2 @click="drawer = true">声学：折线图</h2>
          <h2 @click="saveQrCode">下载</h2>
        </div>
        
      </el-header>
      
      <!-- <button class="ImportButton" type="button" name="seach" @click="FuncCSVInport">
            CSV Import
      </button> -->

      <el-button class="ImportButton" type="button" name="seach" @click="FuncCSVInport">
            CSV Import
    </el-button>

<el-drawer
  title="功能选择"
  :visible.sync="drawer"
  :direction="direction">
  <el-row class="tac">
  <el-col :span="24">
    <el-menu
      default-active="2"
      class="el-menu-vertical-demo"
      @open="handleOpen">
      <el-submenu index="1">
        <template slot="title">
          <i class="el-icon-location"></i>
          <span>声学</span>
        </template>
        <el-menu-item-group>
          <el-menu-item index="1-1" @click="clickMenu('1-1')">折线</el-menu-item>
          <el-menu-item index="1-2" @click="clickMenu('1-2')">cpk</el-menu-item>
        </el-menu-item-group>
      </el-submenu>

      <el-submenu index="2">
        <template slot="title">
          <i class="el-icon-location"></i>
          <span>光学</span>
        </template>
        <el-menu-item-group>
          <el-menu-item index="2-1" @click="clickMenu('2-1')">箱图</el-menu-item>
        </el-menu-item-group>
      </el-submenu>

      <!-- <el-submenu index="3">
        <template slot="title">
          <i class="el-icon-location"></i>
          <span>SMT</span>
        </template>
        <el-menu-item-group>
          <el-menu-item index="3-1" @click="clickMenu('3-1')">折线图</el-menu-item>
          <el-menu-item index="3-1" @click="clickMenu('3-2')">cpk</el-menu-item>
        </el-menu-item-group>
      </el-submenu> -->
    </el-menu>
  </el-col>
</el-row>

</el-drawer>

      <!-- 嵌套容器 -->
      <el-container>
        <!-- 侧边导航菜单 -->
        <!-- <el-aside width="150px"></el-aside> -->
        <!-- 内容 -->
        <el-main>
          <!-- 第一列栅格布局 -->
          <el-row>
            <el-col :span="12" class="col1">
              <el-table :data="allData" ref="multipleTable" 
                v-el-table-infinite-scroll="load" border stripe
                height="300px" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column
                  type="index"
                  label="序号"
                  width="60"
                ></el-table-column>
                <el-table-column prop="SerialNumber" label="SN"></el-table-column>
                <el-table-column prop="StartTime" label="StartTime"></el-table-column>
                <el-table-column prop="EndTime" label="EndTime"></el-table-column>
              </el-table>
            </el-col>
            <el-col :span="12" class="col2">
               <el-table :data="allItem" ref="multipleTable" 
                v-el-table-infinite-scroll="load" highlight-current-row border @current-change="handleCurrentChange"
                height="300px">
                <el-table-column
                  type="index"
                  label="序号"
                  width="60"
                ></el-table-column>
                <el-table-column prop="ItemName" label="Item Name"></el-table-column>
              </el-table>             
            </el-col>
            
          </el-row>
          <!-- 第二列布局 -->
          <el-row>
            <el-col :span="24" class="col3">
              <!-- 导出csv -->
              <!-- 创建隐藏file input -->
              <input
                type="file"
                id="files"
                ref="refFile"
                v-on:change="importCsv"
                style="opacity: 0"
              />
              <div id="saveImage" ref="qrCodeDiv">
                  <div class="titlestyle">{{title}}</div>
                <div id="myChart" :style="{ height: '350px' }"></div>
              </div>
              
            </el-col>
          </el-row>
        </el-main>
      </el-container>
      <!-- 底栏 -->
      <!-- <div @click="saveQrCode">下载图片</div> -->
      <el-footer height="30px">&copy;预留底部标签</el-footer>
    </el-container>
  </div>
</template>

<script>
import Papa from "papaparse";
import elTableInfiniteScroll from 'el-table-infinite-scroll'
import html2canvas from "html2canvas";
var chartManager;
export default {
  name: "HelloWorld",
  directives: {
    'el-table-infinite-scroll': elTableInfiniteScroll
  },
  data() {
    return {
      msg: "Welcome to Your Vue.js App",
      imgUrl: "",
      drawer: false,
      direction: 'ltr',
      clientHeight:'',
      allData:[],
      allBeginData:[],
      allItem:[],
      chatData:[],
      endLindata:[],
      multipleSelection: [],
      currentRow: null,
      title: "",
      itemList: [
        {
          name: "a",
          type: "P000001",
          price: "￥88888",
        },
        {
          name: "b",
          type: "P000002",
          price: "￥2000",
        },
      ]
    };
  },
  mounted() {
// 获取浏览器可视区域高度
      this.clientHeight =   `${document.documentElement.clientHeight}`          //document.body.clientWidth;
      //console.log(self.clientHeight);
      window.onresize = function temp() {
        this.clientHeight = `${document.documentElement.clientHeight}`;
      };
},
watch: {
      // 如果 `clientHeight` 发生改变，这个函数就会运行
      clientHeight: function () {
        this.changeFixed(this.clientHeight)
      }
    },

  methods: {
    saveQrCode () {
      html2canvas(this.$refs.qrCodeDiv).then(canvas => {
        const link = document.createElement('a')
        link.href = canvas.toDataURL()
        link.setAttribute('download', this.title + '.png')
        link.style.display = 'none'
        document.body.appendChild(link)
        link.click()
      })
    },
    handleOpen(key, keyPath) {
        console.log(key, keyPath);
      },
      // handleClose(key, keyPath) {
      //   console.log(key, keyPath);
      // },
    clickMenu(value){
      if(value=="1-1"){
        this.$router.push({path:'/',query:{}});
      }
      if(value=="1-2"){
        this.$router.push({path:'/VidioCpk',query:{}});
      }
      if(value=="2-1"){
        this.$router.push({path:'/BoxLink',query:{}});
      }
   
      console.log(value)
    },
    changeFixed(clientHeight){                        //动态修改样式
        console.log(clientHeight);
        this.$refs.homePage.style.height = clientHeight+'px';

      },

      load(){},
    //多选
    handleSelectionChange(val) {
      // console.log(333333333333333+val)
      this.multipleSelection = val;
      console.log("888888888")

      this.SelectFinish();

    },
    //单选
    handleCurrentChange(val) {


        this.title = val.ItemName;
        console.log(val.ItemName)
        this.currentRow = val;
        this.SelectFinish();




    },
    importCsv() {
      console.log('++++++++')
      let selectedFile = null;
      selectedFile = this.$refs.refFile.files[0];
      if (selectedFile === undefined) {
        return;
      }
      var reader = new FileReader();
      reader.readAsDataURL(selectedFile);
      reader.onload = (evt) => {
        // 检查编码
        // let encoding = this.checkEncoding(evt.target.result);
        // 将csv转换成二维数组
        Papa.parse(selectedFile, {
          encoding: "ANSI",
          complete: (res) => {
            // UTF8 \r\n与\n混用时有可能会出问题
            let data = res.data;
            if (data[data.length - 1] == "") {
              //去除最后的空行
              data.pop();
            }
            this.allData = data;
            this.allBeginData=data;
            this.VidioBrokeline();
          },
        });
      };
    },
    VidioBrokeline() {
      var datas = [];
      let first = this.allData[1];
      var headers = first;
      for (var i = 7; i < this.allData.length; i++) {
        var datal = {};
        var temp = this.allData[i];
        for (var j = 0; j < temp.length; j++) {
          datal[headers[j]] = temp[j];
        }
        if (datal.Site != "") {
          datas.push(datal);
        }
      }
      console.log(datas);  // data就是文件里面的数据
      this.allData = datas;
      const items = new Set();
      for(var i=0;i<headers.length;i++){
        var str=headers[i]
        if(str.indexOf("@")!=-1){
            var csvarry = str.split("@");  
            items.add(csvarry[0]) ;
        }
      }
      var itemArray =Array.from(items)  ;
      for(var j=0;j<itemArray.length;j++){
         var datal = {};
          datal["ItemName"] = itemArray[j];
         this.allItem.push(datal);
      }
      this.SelectFinish();
    },
    LineDetailData(obj, str) {
      var listMap = obj;
      var datas = {};
      var allkey = [];
      var allValue = [];
      Object.keys(listMap).forEach(function (key) {
        var csvarry = key.split("@");
        if (csvarry[0] == str) {
          var datal = {};
          datas[csvarry[1]] = listMap[key];
          allkey.push(csvarry[1]);
          allValue.push(listMap[key]);
        }
      });
      this.chatData = datas;
      return datas;
    },

  SelectFinish() {
    console.log("88888899999")
    console.log(this.currentRow)
    console.log(this.multipleSelection)
    if(this.currentRow!=null &&this.multipleSelection.length>0){
      var valueDataArr = [];
      var keyData = [];
      var snName=[];
      for (var i = 0; i < this.multipleSelection.length; i++) {
        var Obj = this.multipleSelection[i];
        var datas = this.LineDetailData(Obj, this.currentRow.ItemName);
        keyData = Object.keys(datas);
        var valueData = Object.values(datas);
        valueDataArr.push(valueData);
        var sn = this.multipleSelection[i].SerialNumber + "=> " + this.multipleSelection[i].StartTime;
        snName.push(sn);
      }
      console.log(valueDataArr.length)

      //画limit
      // console.log("555555")
      // console.log(keyData)
      // console.log(valueDataArr)
      // console.log(snName)
      // console.log(this.currentRow.ItemName)
      // console.log("6666")

      var datas = [];
      let first = this.allBeginData[1];
      var headers = first;
      for (var i = 4; i < 6; i++) {
        var datal = {};
        var temp = this.allBeginData[i];
        for (var j = 0; j < temp.length; j++) {
          datal[headers[j]] = temp[j];
        }
        if (datal.Site != "") {
          datas.push(datal);
        }
      }
      var listStr = this.currentRow.ItemName;
      var allValue = [];
      Object.keys(datas[0]).forEach(function (key) {
        var csvarry = key.split("@");
        console.log(listStr)
        if (csvarry[0] == listStr) {
          allValue.push(datas[0][key]);
        }
      });
      valueDataArr.push(allValue)
      snName.push(datas[0].Site)
      console.log(allValue)
      console.log(datas[0].Site)
      var allValue2 = [];
      Object.keys(datas[1]).forEach(function (key) {
        var csvarry = key.split("@");
        if (csvarry[0] == listStr) {
          allValue2.push(datas[1][key]);
        }
      });
      valueDataArr.push(allValue2)
      snName.push(datas[1].Site)

      this.drawLine(keyData, valueDataArr, snName);
      

    }

  },
    drawLine(allkey, allValue, snName) {
      if (chartManager != null && chartManager != "" && chartManager != undefined){
        chartManager.dispose();
      }
      chartManager = this.$echarts.init(document.getElementById("myChart"));
                //随着屏幕大小调节图表
          window.addEventListener("resize", () => {
          chartManager.resize();
        });
      console.log("55555555");
      console.log(allValue);
            console.log(snName);

      var ser = [];
      for (var i = 0; i < allValue.length; i++) {
        if(snName[i]=="Upper Limit ----->"|| snName[i]=="Lower Limit ----->"){
              var dic = {
              name: snName[i],
              type: "line",
              // stack: "Total",
              smooth:'true',
              data: allValue[i],
              symbolSize: 0,
              itemStyle : {  
                  normal : {  
                  lineStyle:{  
                            color:'	#DC143C'  
                      }  
                    }  
              },
            };
            ser.push(dic);

        }else{
          var dic = {
            name: snName[i],
            type: "line",
            // stack: "Total",
            smooth:'true',
            data: allValue[i],
            symbolSize: 0,
          };
          ser.push(dic);
        }

      }
      console.log(ser);

      // 绘制图表
      chartManager.setOption({
        // tooltip: {
        //   trigger: 'axis'
        // },
        // toolbox: {
        // feature: {
        //   //  saveAsImage: {}
        //   }
        // },
        // legend: {
        //     // data: snName
        // },
        xAxis: {
          data: allkey,
                      
            axisLabel: {
              interval: 0,
             formatter: function (value, index) {
                if(value=="50"||value=="100"||value=="1000"||value=="2000"||value=="10000"||value=="20000"){
                  return value ;
               }else{
                 return " ";
               }

            }
            }
        },
        yAxis: {},
        series: ser,
      });

    },
    
    FuncCSVInport() {
      // 使用vue的ref参数直接操作input的点击事件触发 importCsv
      this.$refs.refFile.dispatchEvent(new MouseEvent("click"));
    },
  },
};
</script>

<style scoped>

.el-header {
  background-color: #409eff;
  color: white;
  display:flex;
  text-align: left;
	flex-direction: column;
	justify-content: space-between;
}

.el-main{
  padding: 0px;
}
.el-footer {
  background-color: #909399;
  color: black;
  text-align: center;
}
.el-aside {
  background-color: chartreuse;
}
.el-main {
  background-color: darkkhaki;
}
.el-col {
  height: 300px;
}
.titlestyle{
  margin-bottom: 20px;
}
.col1 {
  background-color: rgb(36, 128, 0);
  height: 45%;
}
.col2 {
  background-color: tomato;
  height: 45%;
}
.col3 {
  background-color: rgb(215, 233, 207);
  height: 45%;
}
.ImportButton{
}
.headerDiv{
  display: flex;
  justify-content: space-between
}

</style>
